package com.pactera.madp.cp.common.util.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.madp.cp.common.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;

import static com.pactera.madp.cp.common.constant.WxAccountApiConst.*;

@Slf4j
public class WxAccountApiUtils {

    private static final String CONST_ACCESS_TOKEN_INVALID = "-1";

    private static String doGet(String url, String key) {
        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
        log.debug("url: " + url);
        String respJson = HttpClientUtil.doGet(url);
        log.debug("respJson: " + respJson);
        log.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
        return getResult(respJson, key);
    }

    private static String doPost(String url, String key, String requestBody) {
        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
        log.debug("url: " + url);
        log.debug("requestBody: " + requestBody);
        String respJson = HttpClientUtil.doPost(url, requestBody);
        log.debug("respJson: " + respJson);
        log.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
        return getResult(respJson, key);
    }

    private static String getResult(String result, String key) {
        log.debug(key + " : " + result);

        JSONObject jsonObject = JSON.parseObject(result);
        int errCode = jsonObject.getIntValue("errcode");
        if (errCode == -1) {
            return CONST_ACCESS_TOKEN_INVALID;
        }
        if (key == null) {
            return "";
        } else if (key.isEmpty()) {
            return result;
        } else {
            return jsonObject.getString(key);
        }
    }

    /**
     * 获取公众号token
     * @param appId
     * @param secret
     * @return
     */
    public static String getAccountAccessToken(String appId, String secret) {
        String url = API_GET_TOKEN.replace("APPID", appId).replace("APPSECRET", secret);
        String key = "access_token";
        String respJson = doGet(url, key);
        if (CONST_ACCESS_TOKEN_INVALID.equals(respJson)){
            respJson = doGet(url, key);
        }
        return respJson;
    }

    /**
     * 获取临时票据
     * @param accessToken 全局token
     * @return
     */
    public static String getAccountTicket(String accessToken) {
        String url = API_GET_TICKET.replace("ACCESS_TOKEN", accessToken);
        String key = "ticket";
        String respJson = doGet(url, key);
        if (CONST_ACCESS_TOKEN_INVALID.equals(respJson)){
            respJson = doGet(url, key);
        }
        return respJson;
    }
}
